package com.hmyuan.webdesktop.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.hmyuan.webdesktop.domain.User;


public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
        User user = (User) request.getSession().getAttribute("current_user");
        if(user==null) {
        	if("POST".equals(request.getMethod())) {
        		Map<String, Object> result = new HashMap<String, Object>();
        		result.put("code", 2);
        		result.put("msg", "尚未登录！");
        		response.setContentType("application/json");
        		response.setCharacterEncoding("UTF-8");
        		response.getWriter().print(new JSONObject(result).toJSONString());
        	}else {
        		response.sendRedirect(request.getContextPath()+"/login.html");
        	}
        	return false;// 只有返回true才会继续向下执行，返回false取消当前请求
        }else {
        	return true;// 只有返回true才会继续向下执行，返回false取消当前请求
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        //System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        //System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
